<?php

use Illuminate\Support\Facades\Auth;
class RecipeController extends BaseController {
    
	public function index(){
		$with = array( 
			'user',
			'commentsCount',
			'likesDislikes'
		);
		
        $recipes = Recipe::with( $with )->orderBy( 'created_at' )->get();
        
        return View::make( 'layouts.recipes-list', array( 'recipes' => $recipes ) );
    }
    
    public function getRecipeInfo( $id ){
    	$with = array(
    			'user',
    			'likesDislikes',
    			'steps',
    			'commentsCount',
    			'commentsNoAnswersCount',
    			'commentsPagination',
    			'commentsPagination.user',
    			'commentsPagination.likesDislikes',
    			'commentsPagination.answersCount',
    			'commentsPagination.answersPagination',
    			'commentsPagination.answersPagination.user' );
    	$recipe = Recipe::with( $with )->find( $id );
    	
    	// Gets user likes dislikes related to given comments
    	$userLikes = $userDislikes = array();
    	if( Auth::user() ){
	    	$arrayCommentIds = array();
	    	foreach( $recipe->commentsPagination as $c )
	    		$arrayCommentIds[] = $c->id;
	    	
	    	$result = CommentsLikesDislikes::where( 'user_id', '=', Auth::user()->id )
	    		->whereIn( 'comment_id', $arrayCommentIds )->get();
	    	
	    	foreach( $result as $r ){
	    		if( $r->like == 1 )
	    			$userLikes[] = $r->comment_id;
	    		else
	    			$userDislikes[] = $r->comment_id;
	    	}
    	}
    	
    	return View::make( 'layouts.recipe-info', 
    			array( 'recipe' => $recipe, 'userLikes' => $userLikes, 'userDislikes' => $userDislikes ) );
    }
}